package com.seeyon.apps.thirdapp.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.ctp.util.json.JSONUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpRequestUtiltoken {

    private static final Log log = LogFactory.getLog(HttpRequestUtiltoken.class);
    
    public static JSONObject sendPost(String url, String content) {
    	return sendPost(url,content,"json");
    	
    }

    public static JSONObject sendPost(String url, String content, String contentType) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = HttpClients.createDefault();
            int CONNECTION_TIMEOUT = 10 * 1000;
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build();
            httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            if("json".equals(contentType))
            {
            	httpPost.addHeader("Content-Type", "application/json");
            	httpPost.addHeader("Accept", "application/json");
            }
            else
            {
            	httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            StringEntity requestEntity = new StringEntity(content, "UTF-8");
            httpPost.setEntity(requestEntity);
            httpResponse = httpClient.execute(httpPost, new BasicHttpContext());
            HttpEntity entity = httpResponse.getEntity();
            if(entity != null) {
                String resultStr = EntityUtils.toString(entity, "UTF-8");
                JSONObject result = null;
                try{
                	result= JSONObject.parseObject(resultStr);
                }catch(Exception e)
                {
                	result=new JSONObject();
                	result.put("msg",resultStr);
                }
                return result;
            }
        } catch(Exception e) {
            log.error("", e);
        } finally {
            if(httpResponse != null) {
                try {
                    httpResponse.close();
                } catch(Exception e) {
                }
            }
            if(httpPost != null) {
                try {
                    httpPost.releaseConnection();
                } catch(Exception e) {
                }
            }
            if(httpClient != null) {
                try {
                    httpClient.close();
                } catch(Exception e) {
                }
            }
        }
        return null;
    }

    public static JSONObject sendGet(String url) {
    	HttpClient httpClient =null;
        HttpGet httpGet=null;
        HttpResponse response=null;
        try{
        	httpClient = MySSLSocketFactory.getNewHttpClient();
            httpGet=new HttpGet(url);
            response= httpClient.execute(httpGet);  
            httpGet.addHeader("Content-Type", "application/json");
            int CONNECTION_TIMEOUT = 10 * 1000;
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build();
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-Type", "application/json");
            httpGet.addHeader("Accept", "application/json");
            HttpEntity entity = response.getEntity();
            response.getStatusLine().getStatusCode();
            if(entity != null) {
              String resultStr = EntityUtils.toString(entity, "UTF-8");
              System.out.print("httpRequestUtil返回值信息："+resultStr);
              Map<String,Object> map=new HashMap<String,Object>();
              map.put("id", resultStr);
              //net.sf.json.JSONObject JSONObject=net.sf.json.JSONObject.fromObject(map);
              //提交stuodio时变更

              JSONObject result = JSONObject.parseObject(JSONUtil.toJSONString(map));
             // System.out.println("返回1："+ JSONUtils.toJSON(JSONObject));
              System.out.println("返回1："+ JSONUtil.toJSONString(map));
              return result;
          }
        }catch(Exception ex){
            log.error("ume消息集成：token认证报错：",ex);
            ex.printStackTrace();
        }finally{
        	
              if (httpGet != null)
                try {
                  httpGet.releaseConnection();
                }
                catch (Exception localException8) {
                }
              if(httpClient!=null){
            	  httpClient.getConnectionManager().closeExpiredConnections();
              }
            }
        return null;
    }
    public static String getTokenString(String ticketUrl) {
        String token = "";
        String rt = doGetGetToken(ticketUrl);
        if (rt.contains("id")) {
            JSONObject parseObject = JSON.parseObject(rt);
            token = parseObject.getString("id");
        } else {
            token = rt;
        }
        return token;
    }
    public static String doGetGetToken(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            // 设置请求头信息，鉴权
            httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 请求超时时间
                    .setSocketTimeout(60000)// 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    public static JSONObject sendGetUser(String url, String token) {
    	CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = HttpClients.createDefault();
            int CONNECTION_TIMEOUT = 10 * 1000;
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build();
            httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-Type", "application/json");
            httpGet.addHeader("Accept", "application/json");
            httpGet.addHeader("Authorization", "Bearer "+token);
            httpResponse = httpClient.execute(httpGet, new BasicHttpContext());
            HttpEntity entity = httpResponse.getEntity();
            if(entity != null) {
                String resultStr = EntityUtils.toString(entity, "UTF-8");
                JSONObject result = JSONObject.parseObject(resultStr);
                return result;
            }
        } catch(Exception e) {
            log.error("", e);
        } finally {
            if(httpResponse != null) {
                try {
                    httpResponse.close();
                } catch(Exception e) {
                }
            }
            if(httpGet != null) {
                try {
                    httpGet.releaseConnection();
                } catch(Exception e) {
                }
            }
            if(httpClient != null) {
                try {
                    httpClient.close();
                } catch(Exception e) {
                }
            }
        }
        return null;
    }
    public static void main(String[] args) {
    	Map map=new HashMap();
    	map.put("userName", "restadmin");
    	map.put("password", "restadmin");
    	String ticketUrl="http://10.113.200.66/seeyon/rest/token";
        //System.out.println("消息穿透单点地址："+ticketUrl);
        JSONObject json = HttpRequestUtiltoken.sendPost(ticketUrl, JSONUtil.toJSONString(map));
       // System.out.println(JSONUtil.toJSONString(json));
    }
}
